var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser = require('body-parser');

var app = express();
var server = require('http').Server(app);
// 引入 socket.io
var io = require('socket.io')(server);

var expressSwagger = require('express-swagger-generator')(app);
// var swaggerUi = require('express-swaggerize-ui');
var swaggerOptions = require('./config/swagger');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var searchRouter = require('./routes/search');

var ejs = require("ejs"); //引入ejs

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine("html", ejs.__express);
app.set('view engine', 'ejs');

//一些中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors()); //跨域
app.disable('etag'); //禁止304缓存

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
// parse application/json
app.use(bodyParser.json())

expressSwagger(swaggerOptions)

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/search', searchRouter);

// 可修改
// app.use('/api-docs.json', function (req, res) {
//   res.json(require('./path/to/swaggerize/docs.json'));
// });
// app.use('/api-docs', swaggerUi());

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');
  res.json({
    status: err.status,
    message: err.message
  });
});

// io 各种事件
io.on('connection', function (socket) {
  console.log('websocket has connected')
  socket.emit('message', { hello: '欢迎链接' });
  socket.on('say', function (data) {
    console.log(data);
    if (data.my === '走，一起吃饭吧') {
      socket.emit('eating', { hello: '果断走起呀！' });
      return
    }
    io.sockets.emit('news', { hello: data.my });//socket等价于io.sockets
  });
})

module.exports = app;